package com.begye.smartloan.apptest.huankuan

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtPinHuanKuanSuccessBinding
import com.begye.smartloan.apptest.detailadsource.DetailAdSourceActivity
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.renzheng.RenZhengActivity
import com.begye.smartloan.apptest.renzheng.bangka.RenZhengBangKaActivity
import com.begye.smartloan.apptest.renzheng.document.RenZhengDocumentActivity
import com.begye.smartloan.apptest.renzheng.lianxiren.RenZhengLianXiRenActivity
import com.begye.smartloan.apptest.renzheng.selfie.RenZhengSelfieActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.addTouch
import com.data.datalib.ASSycManager
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.copyLabel
import com.util.utillib.extend.toNextActivity
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog

@SuppressLint("CustomSplashScreen")
class PinHuanKuanSuccessActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtPinHuanKuanSuccessBinding

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtPinHuanKuanSuccessBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onDoingRenZhengPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingLianXiRenPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengLianXiRenActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingBangKaFrPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengBangKaActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingDocumentPageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengDocumentActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onDoingSelfiePageLiveData.observe(this) {
            if (it) {
                toNextActivity(
                    activity = RenZhengSelfieActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            if (it.isNotBlank()) {
                // to shen qing ye
                toNextActivity(
                    activity = DetailAdSourceActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

    }

    private fun configUIEvent() {

        _binding.atPinHuanKuanSuccessNar.initConfig(
            text = getString(R.string.huan_kuan_text_35),
            textColor = "#000000",
            leftResId = R.drawable.dres_39,
            rightResId = R.drawable.dres_38
        ) {
            if (0 == it) {
                toNextActivity(
                    activity = HomeAdSourceActivity::class.java,
                    mode = IntentFlagMode.SINGLE_TOP
                )
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }

        _binding.atPinHuanKuanSuccessApAgain.setOnClickListener {
            _binding.atPinHuanKuanSuccessApAgain.isEnabled = false

            if (checkPermission()) {
                _yongHuLiuChengViewModel.requestYongHuLiuCheng()

                try {
                    ASSycManager.syncData(LoginTool.filterSession()) {}
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            } else {
                requestPermission()
            }

            //
            addTouch(type = "pin_huan_kuan_success_commit_click")
        }

        _binding.atPinHuanKuanSuccessFlowIdCopy.setOnClickListener {
            val text = _binding.atPinHuanKuanSuccessFlowIdValue.text.toString().trim()
            if (text.isNotBlank()) {
                copyLabel(text, "Success")
            }

            //
            addTouch(type = "pin_huan_kuan_success_copy_id_click")
        }

    }

    private fun configUIData() {
        // 查询状态
        val product = intent.getStringExtra("product") ?: ""
        val jinE = intent.getStringExtra("jinEReceived") ?: ""
        val pid = intent.getStringExtra("pid") ?: ""
        val pTime = intent.getStringExtra("pTime") ?: ""

        _binding.atPinHuanKuanSuccessJinEValue.text = jinE
        _binding.atPinHuanKuanSuccessProductValue.text = product
        _binding.atPinHuanKuanSuccessFlowIdValue.text = pid
        _binding.atPinHuanKuanSuccessTime.text = pTime
    }

    private fun checkPermission(): Boolean {
        val list = SysConfigTool.filterShouYeQuanXiang()
        return EasyPermissions.hasPermissions(
            this,
            *(list.toTypedArray<String>())
        )
    }

    private fun requestPermission() {
        val list = SysConfigTool.filterShouYeQuanXiang()
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.disclosure_text_10),
            300,
            *(list.toTypedArray<String>())
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        requestPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        _binding.atPinHuanKuanSuccessApAgain.performClick()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            requestPermission()
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }

}